<template>
  <div>
    <slot name="page-header"></slot>

    <div>
      <a-row :gutter="24">
        <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
          <score :value="79" label="个人评分" />
        </a-col>
        <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
          <score :value="93" label="他人评分" />
        </a-col>
        <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
          <chart-card :loading="missionCompletionRate.loading" title="目标完成率" :total="`${Math.round(missionCompletionRate.finishedRate * 100)}%`">
            <a-tooltip title="目标完成率" slot="action">
              <a-icon type="info-circle-o" />
            </a-tooltip>
            <div>
              <mini-progress color="rgb(19, 194, 194)" :target="60" :percentage="missionCompletionRate.finishedRate" height="8px" />
            </div>
            <template slot="footer">
              <a-statistic title="已完成目标/总目标" :value="missionCompletionRate.finished" :suffix="`/ ${missionCompletionRate.total}`"/>
            </template>
          </chart-card>
        </a-col>
        <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px' }">
          <chart-card :loading="resultCompletionRate.loading" title="结果完成率" :total="`${Math.round(resultCompletionRate.finishedRate * 100)}%`">
            <a-tooltip title="结果完成率" slot="action">
              <a-icon type="info-circle-o" />
            </a-tooltip>
            <div>
              <mini-progress color="rgb(19, 194, 194)" :target="60" :percentage="resultCompletionRate.finishedRate" height="10px" />
            </div>
            <template slot="footer">
              <a-statistic title="已完成结果/总结果" :value="resultCompletionRate.finished" :suffix="`/ ${resultCompletionRate.total}`"/>
            </template>
          </chart-card>
        </a-col>
      </a-row>

      <a-row :gutter="24" type="flex">
        <a-col
          :xl="12"
          :lg="24"
          :md="24"
          :sm="24"
          :xs="24"
          style="margin-bottom: 20px"
        >
          <a-card :loading="missionViewed.loading" :bordered="false" title="情报" :style="{ height: '100%' }" :bodyStyle="{ height: '453px' }">
            <a-row :gutter="68">
              <a-col :xs="24" :sm="24" :style="{ marginBottom: ' 24px'}">
                <smooth :dataSource="missionViewed.viewedData" :scale="missionViewed.viewedDataScale" title="目标被查看次数" :total="missionViewed.total" />
              </a-col>
            </a-row>
            <div class="ant-table-wrapper">
              <a-table
                row-key="missionId"
                size="small"
                :columns="missionViewed.missionTop5TableColumns"
                :dataSource="missionViewed.missionTop5"
                :pagination="{ pageSize: 5 }"
              >
                <span slot="range" slot-scope="record">
                  <trend :flag="record.type === 'add' ? 'up' : 'down'">
                    {{ record.weeklyIncrease * 100 }}%
                  </trend>
                </span>
              </a-table>
            </div>
          </a-card>
        </a-col>

        <a-col
          :xl="12"
          :lg="24"
          :md="24"
          :sm="24"
          :xs="24"
          style="margin-bottom: 20px"
        >
          <a-card
            class="antd-pro-pages-dashboard-analysis-salesCard"
            :loading="instanceDistribution.loading"
            :bordered="false"
            title="团战状态分布"
            :style="{ height: '100%' }"
            :bodyStyle="{ height: '453px' }"
          >
            <div slot="extra" style="height: inherit;">
              <div class="analysis-salesTypeRadio">
                <a-radio-group v-model="instanceDistribution.type">
                  <a-radio-button value="sponsor">发起的团战</a-radio-button>
                  <a-radio-button value="participant">参与的团战</a-radio-button>
                </a-radio-group>
              </div>
            </div>
            <div>
              <pie :pieData="instanceDistribution.pieData" />
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
// 工具
import { convertNumberToTime } from '@/utils/handleTime'

// 组件
import Score from '@/components/Score'
import Pie from '@/components/Pie'
import Smooth from './components/Smooth'
import {
  ChartCard,
  MiniProgress,
  Trend
} from '@/components'

import {
  score,
  mission,
  keyResult,
  // instance,
  viewedMission
} from '@/api/statistics'

import { mockViewedData, mockInstanceDistribution } from '@/utils/mock'

const searchTableColumns = [
  {
    dataIndex: 'index',
    title: '排名',
    width: 90
  },
  {
    dataIndex: 'keyword',
    title: '目标内容'
  },
  {
    dataIndex: 'count',
    title: '访问数次数'
  },
  {
    dataIndex: 'range',
    title: '周涨幅',
    align: 'right',
    sorter: (a, b) => a.range - b.range,
    scopedSlots: { customRender: 'range' }
  }
]
const searchData = []
for (let i = 0; i < 50; i += 1) {
  searchData.push({
    index: i + 1,
    keyword: `搜索关键词-${i}`,
    count: Math.floor(Math.random() * 1000),
    range: Math.floor(Math.random() * 100),
    status: Math.floor((Math.random() * 10) % 2)
  })
}

export default {
  name: 'ActorBase',
  props: {
    actorId: {
      type: Number,
      required: true
    }
  },
  components: {
    Score, // 分数
    Pie, // 饼状
    Smooth, // 区域图
    ChartCard,
    MiniProgress,
    Trend
  },
  data () {
    return {
      // 评分
      score: {
        loading: false,
        selfScore: 0,
        avgScore: 0
      },

      // 目标完成率
      missionCompletionRate: {
        loading: false,
        finished: 0,
        total: 0,
        finishedRate: 0
      },

      // 目标完成率
      resultCompletionRate: {
        loading: false,
        finished: 0,
        total: 0,
        finishedRate: 0
      },

      // 团战分布
      instanceDistribution: {
        loading: false,
        type: 'sponsor',
        pieData: []
      },

      // 情报
      missionViewed: {
        loading: false,
        missionTop5: [],
        missionTop5TableColumns: [
          {
            dataIndex: 'missionContent',
            title: '目标内容'
          },
          {
            dataIndex: 'totalViewed',
            title: '访问数次数',
            sorter: (a, b) => a.totalViewed - b.totalViewed
          },
          {
            key: 'range',
            title: '周涨幅',
            align: 'right',
            sorter: (a, b) => {
              if (a.type === 'add' && b.type === 'add') {
                return a.totalViewed - b.totalViewed
              } else if (a.type === 'add') {
                return true
              } else if (b.type === 'add') {
                return false
              } else {
                return b.totalViewed - a.totalViewed
              }
            },
            scopedSlots: { customRender: 'range' }
          }
        ],
        viewedData: [],
        viewedDataScale: [
          {
            dataKey: 'x',
            alias: '时间'
          },
          {
            dataKey: 'y',
            alias: '访问数',
            min: 0,
            max: 1000
        }
        ]
      },

      // 情报
      loading: false,
      searchTableColumns,
      searchData
    }
  },
  mounted () {
    this.getScore() // 获取评分
    this.getMissionCompletionRate() // 目标完成率
    this.getKeyResultCompletionRate() // 目标完成率
    this.getViewedMission() // 目标访问数据
    this.getInstanceDistribution() // 团战分布
  },
  methods: {
    // 获取评分
    async getScore () {
      try {
        this.score.loading = true
        const { selfScore, avgScore } = await score({
          actorId: this.actorId
        })
        this.score.selfScore = Number(selfScore)
        this.score.avgScore = Number(avgScore)
      } catch (error) {
        console.log(error)
      } finally {
        this.score.loading = false
      }
    },
    // 目标完成率
    async getMissionCompletionRate () {
      try {
        this.missionCompletionRate.loading = true
        const { finished, finishedRate, total } = await mission({
          actorId: this.actorId
        })
        this.missionCompletionRate.finished = finished
        this.missionCompletionRate.total = total
        this.missionCompletionRate.finishedRate = finishedRate
      } catch (error) {
        console.log(error)
      } finally {
        this.missionCompletionRate.loading = false
      }
    },
    // 结果完成率
    async getKeyResultCompletionRate () {
      try {
        this.resultCompletionRate.loading = true
        const { finished, finishedRate, total } = await keyResult({
          actorId: this.actorId
        })
        this.resultCompletionRate.finished = finished
        this.resultCompletionRate.total = total
        this.resultCompletionRate.finishedRate = finishedRate
      } catch (error) {
        console.log(error)
      } finally {
        this.resultCompletionRate.loading = false
      }
    },
    // 团战分布
    async getInstanceDistribution () {
      try {
        this.instanceDistribution.loading = true
        // const pieData = await instance({
        //   type: this.instanceDistribution.type,
        //   actorId: this.actorId
        // })
        // TODO:
        const pieData = await mockInstanceDistribution({
          type: this.instanceDistribution.type,
          actorId: this.actorId
        })

        this.instanceDistribution.pieData = pieData
      } catch (error) {
        console.log(error)
      } finally {
        this.instanceDistribution.loading = false
      }
    },
    // 目标访问数据
    async getViewedMission () {
      try {
        let max = 0; let total = 0
        this.missionViewed.loading = true
        const {
          missionTop5
        } = await viewedMission({
          actorId: this.actorId
        })
        // console.log(viewedData)

        // TODO:mock
        const viewedData = mockViewedData()
        this.missionViewed.missionTop5 = missionTop5
        this.missionViewed.viewedData = viewedData.map(item => {
          const { visitDate, visitTimes } = item
          if (visitTimes > max) { max = visitTimes }
          total += visitTimes
          return {
            x: convertNumberToTime(visitDate),
            y: visitTimes
          }
        })
        this.missionViewed.viewedDataScale[1].max = max
        this.missionViewed.total = total
      } catch (error) {
        console.log(error)
      } finally {
        this.missionViewed.loading = false
      }
    }
  },
  watch: {
    'instanceDistribution.type' () {
      this.getInstanceDistribution()
    }
  }
}
</script>

<style lang="less" scoped>
.antd-pro-pages-dashboard-analysis-salesCard {
  height: calc(100% - 24px);
  /deep/ .ant-card-head {
    position: relative;
  }
}

.analysis-salesTypeRadio {
  position: absolute;
  right: 24px;
  bottom: 12px;
}
</style>
